package com.nrgedge.setup;

import info.magnolia.cms.beans.config.VirtualURIManager;
import info.magnolia.cms.util.ContentUtil;
import info.magnolia.context.MgnlContext;
import info.magnolia.jcr.util.NodeUtil;
import info.magnolia.module.ModuleLifecycle;
import info.magnolia.module.ModuleLifecycleContext;
import info.magnolia.repository.RepositoryConstants;

import javax.inject.Inject;
import javax.jcr.LoginException;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.PathNotFoundException;
import javax.jcr.RepositoryException;

public class VanityUrlModule implements ModuleLifecycle {

	private final VirtualURIManager virtualURIManager;

	@Inject
	public VanityUrlModule(VirtualURIManager virtualURIManager) {
		this.virtualURIManager = virtualURIManager;
	}

	public void start(ModuleLifecycleContext ctx) {
		try {
			Node mappings = MgnlContext.getJCRSession(RepositoryConstants.CONFIG).getNode("/modules/" + ctx.getCurrentModuleDefinition().getName() + "/virtualURIMapping");

			NodeIterator folders = NodeUtil.filterNodeType(mappings.getNodes(), "mgnl:content");
			while (folders.hasNext()) {
				Node folder = folders.nextNode();
				virtualURIManager.register(ContentUtil.asContent(folder));
			}

		} catch (PathNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (LoginException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (RepositoryException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//virtualURIManager.register(node);
	}

	public void stop(ModuleLifecycleContext moduleLifecycleContext) {

	}

}
